package com.lmabbe.tenant.service.impls;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lmabbe.tenant.mapper.SysDicItemMapper;
import com.lmabbe.tenant.mapper.SysDicMapper;
import com.lmabbe.tenant.objects.converter.SysDicConverter;
import com.lmabbe.tenant.objects.converter.SysDicItemConverter;
import com.lmabbe.tenant.objects.entity.SysDic;
import com.lmabbe.tenant.objects.entity.SysDicItem;
import com.lmabbe.tenant.objects.query.SysDicItemQuery;
import com.lmabbe.tenant.objects.vo.SysDicTreeVo;
import com.lmabbe.tenant.service.SysDicService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统字典
 *
 * @author lmabbe
 */
@Service
@RequiredArgsConstructor
public class SysDicServiceImpl extends ServiceImpl<SysDicMapper, SysDic>
        implements SysDicService {
    private final SysDicConverter sysDicConverter;
    private final SysDicItemConverter sysDicItemConverter;
    private final SysDicItemMapper sysDicItemMapper;

    @Override
    public IPage<SysDicItem> items(Long dicId, SysDicItemQuery query) {
        return sysDicItemMapper.selectPage(query.createPage(), query.createQuery());
    }

    @Override
    public SysDicItem item(Long itemId) {
        return sysDicItemMapper.selectById(itemId);
    }

    @Override
    public void delresource(Long itemId) {
        sysDicItemMapper.deleteById(itemId);
    }

    @Override
    public void addItem(SysDicItem item) {
        sysDicItemMapper.insert(item);
    }

    @Override
    public void editItem(SysDicItem resource) {
        sysDicItemMapper.updateById(resource);
    }

    @Override
    public List<SysDicTreeVo> allTree() {
        List<SysDicTreeVo> result = new ArrayList<>();
        List<SysDic> list = this.list();
        List<SysDicItem> sysDicItems = sysDicItemMapper.selectList(Wrappers.emptyWrapper());
        for (SysDic sysDic : list) {
            List<SysDicItem> collect = sysDicItems.stream().filter(item -> item.getDicId().equals(sysDic.getDicId())).collect(Collectors.toList());
            SysDicTreeVo sysDicTreeVo = sysDicConverter.toDictTreeVo(sysDic, sysDicItemConverter.list2Vos(collect));
            result.add(sysDicTreeVo);
        }
        return result;
    }
}
